package com.aaa.filter;

import cn.hutool.core.util.ObjectUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2022/6/14 14:07
 * @description：登录过滤器，拦截非法用户，或者session过期用户
 * @modified By：
 * @version: 1.0
 */
@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
       // System.out.println("登录过滤器开始生效啦");


        //session中有userInfo放行，否则调转到登录页面
        HttpServletRequest  httpServletRequest= (HttpServletRequest) request;

        String contextPath = httpServletRequest.getContextPath();
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        HttpSession session = httpServletRequest.getSession();

        //放行登录页面login.jsp
        String uri = httpServletRequest.getRequestURI();
        if(uri.contains("login")){
            chain.doFilter(request,response);
        }else {
            if(ObjectUtil.isNotEmpty(session.getAttribute("user"))){
                //放行
                chain.doFilter(request,response);
            }else {
                httpServletResponse.sendRedirect(contextPath+"/login.jsp");
            }
        }


    }
}
